<!-- 页面标注 -->
<html>

<head>
	<meta charset="UTF-8" />
	<meta name="viewport"
		content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
	<title>主体标注</title>
	<link rel="stylesheet" href="./styles/route.css">
	<link rel="stylesheet" href="./js/leaflet/leaflet.css">
	<script type="text/javascript" src="./js/leaflet/leaflet.js"></script>
	<!-- Leaflet Routing Machine -->
	<link rel="stylesheet" href="./js/leaflet-routing-machine/leaflet-routing-machine.css">
	<script src="./js/leaflet-routing-machine/leaflet-routing-machine.min.js"></script>
	<!-- Leaflet TrackPlayer -->
	<script src="./js/leaflet-trackplayer/leaflet-trackplayer.umd.cjs"></script>
	<style>
		.car-icon {
			width: 20px;
			height: 20px;
		}
	</style>
</head>

<body>
	<div style="position: absolute;z-index:2" id="map"></div>
</body>
<script type="text/javascript" src="./js/jquery.min.js"></script>
<script type="text/javascript" src="./js/uni.webview.1.5.6.js"></script>
<script type="text/javascript" src="./js/map-util.js"></script>
<script type="text/javascript">
	var map = null;// 地图实例 
	var trackPlayer = null; // 轨迹播放器
	var lngLatList = []; // 坐标点列表
	var routeCoords = []; // 路线坐标列表
	var markers = []; // 存储所有标记
	var routeControl = null; // 路由控制器
	var companyMarkers = []; // 企业标记

	//初始化地图
	document.addEventListener("DOMContentLoaded", function () {
		initMap();
	});

	function initMap() {
		// 初始化地图
		map = L.map('map', {
			center: [39.085318, 117.201509], // 注意：Leaflet中是[lat, lng]
			zoom: 12,
			zoomControl: false
		});

		// 添加高德地图瓦片图层
		L.tileLayer('https://wprd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}', {
			subdomains: ['1', '2', '3', '4'],
			attribution: '&copy; 高德地图'
		}).addTo(map);

		// 通知uni-app加载企业列表
		uni.postMessage({
			data: { type: 'loadCompanyList' }
		});
		makePoints(`[
			{
				"companyId": "",
				"companyName": "",
				"lngLat": "126.543736,45.827442"
			},
			{
				"companyId": 805495,
				"companyName": "天津市滨海新区欣美幼儿园",
				"lngLat": "117.589215,39.035694"
			},
			{
				"companyId": 805309,
				"companyName": "天津市河东区如意华洋饭店",
				"lngLat": "117.245938,39.136156"
			}
		]`)

	}

	/**
	 * 统一处理所有企业路线
	 * @param {Object} points 所有坐标
	 */
	function makePoints(points) {
		if (points == '' || points == null) {
			uni.postMessage({
				data: { type: 'toast', message: '坐标数据为空!', icon: 'error' }
			});
			setTimeout(function () {
				uni.postMessage({
					data: { type: 'back' }
				});
			}, 1000);
			return;
		}

		// 清空之前的数据
		lngLatList = [];
		routeCoords = [];

		// 清除之前的标记和路线
		clearMapElements();

		var pointsJSON = JSON.parse(points);
		var pointArr = [];

		for (var i = 0; i < pointsJSON.length; i++) {
			pointArr.push(pointsJSON[i].lngLat);
		}

		// uni.postMessage({
		// 	data: { type: 'loading', message: '正在获取路线信息' }
		// });

		try {
			var lngLatArr = []; // 存储经纬度对象

			// 处理坐标并创建标记
			for (var i = 0; i < pointArr.length; i++) {
				let coords = pointArr[i].split(",");
				let lng = parseFloat(coords[0]);
				let lat = parseFloat(coords[1]);

				// WGS84坐标转GCJ02坐标
				let gcj02 = wgs84togcj02(lng, lat);
				lngLatArr.push([gcj02.lat, gcj02.lng]); // Leaflet使用[lat, lng]格式
			}

			// 创建标记
			createMarkers(lngLatArr, pointsJSON, function () {
				// 地图中心移动到第一个坐标
				map.setView(lngLatArr[0], 12);
			});

			// 规划路线
			if (lngLatArr.length > 1) {
				debugger
				calculateRoute(lngLatArr);
			}
		} catch (e) {
			console.error(e);
			uni.postMessage({
				data: { type: 'toast', message: '线路规划失败', icon: 'error' }
			});
		}
	}

	// 清除地图上的元素
	function clearMapElements() {
		// 清除标记
		companyMarkers.forEach(function (marker) {
			map.removeLayer(marker);
		});
		companyMarkers = [];

		// 清除路由控制
		if (routeControl) {
			map.removeControl(routeControl);
			routeControl = null;
		}

		// 停止轨迹播放
		if (trackPlayer) {
			trackPlayer.stop();
			trackPlayer = null;
		}
	}

	// 创建标记
	function createMarkers(lngLatArr, pointsJSON, callback) {
		for (var i = 0; i < lngLatArr.length; i++) {
			if (pointsJSON[i] == null) {
				continue;
			}

			// 创建标记
			var marker = L.marker(lngLatArr[i], {
				title: pointsJSON[i].companyName
			}).addTo(map);

			// 添加信息到标记
			marker.pointData = {
				companyId: pointsJSON[i].companyId,
				companyName: pointsJSON[i].companyName
			};

			// 添加点击事件
			marker.on('click', function (e) {
				var companyId = e.target.pointData.companyId;
				if (companyId == null || companyId == '') {
					uni.postMessage({
						data: { type: 'toast', message: "该点位是当前坐标", icon: 'error' }
					});
					return;
				}
				uni.postMessage({
					data: { type: 'toCompanyInfo', companyId: companyId }
				});
			});

			// 添加标签
			marker.bindTooltip(pointsJSON[i].companyName, {
				permanent: true,
				direction: 'top',
				offset: [0, -10]
			});

			companyMarkers.push(marker);
		}

		if (callback) {
			callback();
		}
	}

	// 计算路线
	function calculateRoute(lngLatArr) {
		if (lngLatArr.length < 2) return;

		// 创建路由控制
		var waypoints = [];
		lngLatArr.forEach(function (point) {
			waypoints.push(L.latLng(point[0], point[1]));
		});

		// 配置路由控制器
		routeControl = L.Routing.control({
			waypoints: waypoints,
			lineOptions: {
				styles: [{ color: '#2C64A7', weight: 5, opacity: 0.9 }],
				extendToWaypoints: true,
				missingRouteTolerance: 0
			},
			show: false, // 不显示路线详情面板
			addWaypoints: false, // 不允许添加途径点
			routeWhileDragging: false, // 不允许拖动
			draggableWaypoints: false, // 不允许拖动途径点
			fitSelectedRoutes: false, // 不自动缩放到路线
			createMarker: function () { return null; } // 不创建默认标记
		}).addTo(map);

		// 路由计算完成后的处理
		routeControl.on('routesfound', function (e) {
			// uni.postMessage({
			// 	data: { type: 'closeLoading' }
			// });

			var routes = e.routes;
			if (routes && routes.length > 0) {
				// 获取路线坐标
				var coordinates = routes[0].coordinates;
				routeCoords = coordinates;

				// 创建轨迹播放器
				createTrackPlayer(coordinates);
			}
		});

		// 路由错误处理
		routeControl.on('routingerror', function (e) {
			uni.postMessage({
				data: { type: 'toast', message: e.error, icon: 'none' }
			})
			console.error('路线计算错误:', e.error);
			// uni.postMessage({
			// 	data: { type: 'toast', message: '路线计算失败', icon: 'error' }
			// });
			// uni.postMessage({
			// 	data: { type: 'closeLoading' }
			// });
		});
	}

	// 创建轨迹播放器
	function createTrackPlayer(coordinates) {
		if (trackPlayer) {
			trackPlayer.stop();
		}

		// 自定义车辆图标
		var carIcon = L.divIcon({
			html: '<div style="transform: rotate(90deg);"><img src="./img/yuandian.png" class="car-icon"></div>',
			className: 'car-marker',
			iconSize: [24, 24],
			iconAnchor: [12, 12]
		});

		// 创建轨迹播放器 - 修复初始化方式
		trackPlayer = L.TrackPlayer(coordinates, {
			map: map,
			maxDistance: 1000, // 最大显示距离
			interval: 20, // 刷新间隔
			speed: 150, // 播放速度
			marker: {
				icon: carIcon
			},
			line: {
				color: '#2C64A7',
				weight: 5,
				opacity: 0.9
			}
		});
	}

	// 开始播放轨迹
	function startCar() {
		console.log("开始");
		if (trackPlayer) {
			trackPlayer.start();
		}
	}

	// 暂停播放轨迹
	function pauseCar() {
		console.log("暂停");
		if (trackPlayer) {
			trackPlayer.pause();
		}
	}

	// 停止播放轨迹
	function stopCar() {
		console.log("结束");
		if (trackPlayer) {
			trackPlayer.stop();
		}
	}

	function bacPage() {
		console.log('返回');
		uni.postMessage({
			data: { type: 'back' }
		});
	}
</script>

</html>